package com.sjk.flink.json;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sjk.flink.util.ObjectMapperUtil;

public class KeyConverter {

    /**
     * 只转单个对象
     *
     * @param jsonNode
     * @return
     */
    public static JsonNode convertKeysToLowercase(JsonNode jsonNode) {
        ObjectMapper objectMapper = ObjectMapperUtil.getObjectMapper();
        if (jsonNode.isObject()) {
            ObjectNode objectNode = objectMapper.createObjectNode();
            jsonNode.fields().forEachRemaining(field -> {
                String lowercaseKey = field.getKey().toLowerCase();
                JsonNode value = convertKeysToLowercase(field.getValue());
                objectNode.set(lowercaseKey, value);
            });
            return objectNode;
        } else if (jsonNode.isArray()) {
            ArrayNode arrayNode= objectMapper.createArrayNode();
            for (JsonNode node : jsonNode) {
                JsonNode nextNode = convertKeysToLowercase(node);
                arrayNode.add(nextNode);
            }
            return arrayNode;
        } else {
            return jsonNode;
        }
    }
}